package com.chuangxin.data.core.io;

import com.chuangxin.data.core.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;

/**
 * Created by Dawnwords on 2015/2/1.
 */
public class FileWriter implements DataOutput {

    private String outputPath;
    private boolean append;

    public FileWriter(String outputPath) {
        File outputDir = new File(outputPath);
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }
        this.outputPath = outputPath;
    }

    public FileWriter(String outputPath, boolean append) {
        this(outputPath);
        this.append = append;
    }

    @Override
    public void output(String title, String content) {
        new FileWritingThread(title, content).start();
    }

    class FileWritingThread extends Thread {
        private String title, content;

        public FileWritingThread(String title, String content) {
            this.title = title;
            this.content = content;
        }

        @Override
        public void run() {
            PrintWriter writer = null;
            try {
                title = title.replaceAll("\\?", "？").replaceAll("\"", "”").replaceAll("//", ",").replaceAll(":", "：");
                writer = new PrintWriter(new FileOutputStream(outputPath + File.separator + title, append));
                writer.println(content);
                writer.flush();
            } catch (Exception e) {
                Logger.fail(e.getMessage(), title);
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
        }
    }
}
